package com.mack.controller;

import com.mack.config.CronTaskRegistrar;
import com.mack.entity.SysJobPO;
import com.mack.enums.StatusEnum;
import com.mack.service.ISysJobService;
import com.mack.util.Result;
import com.mack.util.SchedulingRunnable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("task")
public class TaskController {

    @Autowired
    private ISysJobService sysJobService;

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @PostMapping("/add")
    public Result add(@RequestBody SysJobPO sysJob) {
        boolean success = sysJobService.save(sysJob);
        if (!success)
            return Result.error("新增失败");
        else {
            if (sysJob.getJobStatus().equals(StatusEnum.NORMAL.name())) {
                SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
                cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
            }
        }
        return Result.success();
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody SysJobPO sysJob) {
        boolean success = sysJobService.updateById(sysJob);
        if (!success)
            return Result.error("编辑失败");
        else {
            //先移除再添加
            SchedulingRunnable task1 = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
            cronTaskRegistrar.removeCronTask(task1);
            if (sysJob.getJobStatus().equals(StatusEnum.NORMAL.name())) {
                SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
                cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
            }
        }
        return Result.success();
    }


    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") int id) {
        SysJobPO sysJob = sysJobService.getById(id);
        boolean success = sysJobService.removeById(id);
        if (!success)
            return Result.error("删除失败");
        else {
            SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
        }
        return Result.success("删除成功");
    }

}
